package cn.zhz.service;

import cn.zhz.dao.HouseDao;
import cn.zhz.pojo.House;
import cn.zhz.pojo.HouseCondition;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import java.util.List;

public class HouseService {
    private HouseDao houseDao =new HouseDao();

    public List<House> findKeyInfo(House house){
        Transaction tx = null;
        List<House> result = null;
        try {
            tx=houseDao.currentSession().beginTransaction();
            result = houseDao.findKeyInfo(house);
            tx.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
            if(tx!=null)
                tx.rollback();
        }
        return result;
    }

    public List<House> findByConditions(HouseCondition condition){
        Transaction tx = null;
        List<House> houses=null;
        try {
            tx=houseDao.currentSession().beginTransaction();
            StringBuilder hql = new StringBuilder("from House as house where 1=1 ");
            if(condition.getPrice() != null && condition.getPrice()!=0){
                hql.append(" and house.price < :price");
            }
            if(condition.getContact() != null && condition.getContact().length()>0){
                hql.append(" and house.contact = :contact");
            }
            if(condition.getPubDateStart()!=null){
                hql.append(" and house.pubDate > :pubDateStart");
            }
            if(condition.getPubDateEnd()!=null){
                hql.append(" and house.pubDate < :pubDateEnd");
            }
            houses = houseDao.findByConditions(hql.toString(),condition);
            tx.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
            if(tx != null)
                tx.rollback();
        }
        return houses;
    }
}
